let msgStorage = require("../msgstorage");
let disp = require("../../../utils/broadcast");
let LIST_STATUS = {
  SHORT: "scroll_view_change",
  NORMAL: "scroll_view"
};
var app = getApp()
let page = 0;
let Index = 0;
let curMsgMid = ''
let isFail = false
Component({
  properties: {
    username: {
      type: Object,
      value: {},
    },
    list: {
      type: String,
      value: {}
    },
    orders: {
      type: String,
      value: ''
    },
    useropenid: {
      type: String,
      value: ''
    },
    z_name: {
      type: String,
      value: ''
    }
  },
  // pageLifetimes: {
  //   show: function () {
  //     // 页面被展示
  //     console.log(this.properties.z_name)
  //     console.log(this.properties.list)
  //     console.log(this.properties.useropenid)
  //     console.log(this.properties.username)
  //     console.log(this.properties.orders)
  //   },
  // },
  data: {
    view: LIST_STATUS.NORMAL,
    toView: "",
    chatMsg: [],
    __visibility__: false,
  },
  methods: {
    normalScroll() {
      this.setData({
        view: LIST_STATUS.NORMAL
      });
    },

    shortScroll() {
      this.setData({
        view: LIST_STATUS.SHORT
      });
    },

    onTap() {
      this.triggerEvent("msglistTap", null, {
        bubbles: true
      });
    },

    previewImage(event) {
      var url = event.target.dataset.url;
      wx.previewImage({
        urls: [url] // 需要预览的图片 http 链接列表
      });
    },

    getHistoryMsg() {
      let me = this
      let username = this.data.username;
      let myUsername = wx.getStorageSync("myUsername");
      let sessionKey = username.groupId ? username.groupId + myUsername : username.your + myUsername;
      let historyChatMsgs = wx.getStorageSync("rendered_" + sessionKey) || [];
      console.log(timesMsgList.concat(me.data.chatMsg))
      if (Index < historyChatMsgs.length) {
        let timesMsgList = historyChatMsgs.slice(-Index - 10, -Index)

        this.setData({
          chatMsg: timesMsgList.concat(me.data.chatMsg),
          toView: timesMsgList[timesMsgList.length - 1].mid,
        });
        Index += timesMsgList.length;
        if (timesMsgList.length == 10) {
          page++
        }
        wx.stopPullDownRefresh()
      }
    },
    detail(e) {
      var that = this
      var url = e.currentTarget.dataset.url
      var sate = wx.getStorageSync('sate')
      var c_id = url.split("=")[1]
      var uniacid = app.siteInfo.uniacid
      if (sate == 0) {
        app.util.request({
          'url': 'entry/wxapp/Goods.chufangdt',
          data: {
            c_id: c_id
          },
          success: function(res) {
            console.log(res)
            var ispay = res.data.ispay
            var money = res.data.money
            if (ispay == 0 && money !== '0.00') {
              app.util.request({
                'url': that.data.url + 'app/index.php?i=' + uniacid + '&c=entry&a=wxapp&do=Pay&m=hyb_yl',
                header: {
                  "Content-Type": "application/xml"
                },
                method: "GET",
                data: {
                  openid: wx.getStorageSync('openid'),
                  z_tw_money: money
                },
                success: function(res) {
                  console.log(res);
                  wx.requestPayment({
                    'timeStamp': res.data.timeStamp,
                    'nonceStr': res.data.nonceStr, //字符串随机数
                    'package': res.data.package,
                    'signType': res.data.signType,
                    'paySign': res.data.paySign,
                    success: function(res) {
                      wx.navigateTo({
                        url: url,
                      })
                    }
                  })
                }
              })
            } else {
              wx.navigateTo({
                url: url,
              })
            }
          }
        })

      } else {
        wx.navigateTo({
          url: url,
        })
      }

    },
    renderMsg(renderableMsg, type, curChatMsg, sessionKey, isnew) {
      let me = this
      if (curChatMsg.length > 1) {
        this.data.chatMsg.map(function(elem, index) {
          curChatMsg.map(function(item, i) {
            if (elem.mid == item.mid) {
              //me.data.chatMsg.splice(index, 1)
              curChatMsg.splice(i, 1)
            }
          })
        })
      }


      var historyChatMsgs = wx.getStorageSync("rendered_" + sessionKey) || [];
      if (curChatMsg.length) {
        console.log(curMsgMid.substring(curMsgMid.length - 10), curChatMsg[0].mid.substring(curChatMsg[0].mid.length - 10))
      }

      if (curChatMsg.length && curMsgMid.substring(curMsgMid.length - 10) == curChatMsg[curChatMsg.length - 1].mid.substring(curChatMsg[0].mid.length - 10)) {
        curChatMsg[curChatMsg.length - 1].msg.data[0].isSuc = true
        curChatMsg[curChatMsg.length - 1].isSuc = true
      }
      historyChatMsgs = historyChatMsgs.concat(curChatMsg);
      console.log('当前历史', renderableMsg)
      console.log('历史消息', historyChatMsgs)
      var dd_arr = [];
      for (var i = 0; i < historyChatMsgs.length; ++i) {

        var arr = historyChatMsgs[i].msg.data;
        console.log(arr);
        for (var j = 0; j < arr.length; j++) {
          console.log(JSON.parse(arr[j].data));
          var new_arr = JSON.parse(arr[j].data)
          dd_arr.push(new_arr)

        }
        console.log(dd_arr)
        this.setData({
          dd_arr: dd_arr
        })
        // dd_arr.push(msg_data)
        // console.log(msg_data)
      }
      // console.log(JSON.parse(dd_arr));

      if (!historyChatMsgs.length) return;
      if (isnew == 'newMsg') {
        this.setData({
          chatMsg: this.data.chatMsg.concat(curChatMsg),
          // 跳到最后一条
          toView: historyChatMsgs[historyChatMsgs.length - 1].mid,
        });
      } else {
        this.setData({
          chatMsg: historyChatMsgs.slice(-10),
          // 跳到最后一条
          toView: historyChatMsgs[historyChatMsgs.length - 1].mid,
        });
      }

      wx.setStorageSync("rendered_" + sessionKey, historyChatMsgs);

      let chatMsg = wx.getStorageSync(sessionKey) || [];
      chatMsg.map(function(item, index) {
        curChatMsg.map(function(item2, index2) {
          if (item2.mid == item.mid) {
            chatMsg.splice(index, 1)
          }
        })
      })


      wx.setStorageSync(sessionKey, chatMsg);
      Index = historyChatMsgs.slice(-10).length;
      wx.pageScrollTo({
        scrollTop: 9999,
      })

      if (isFail) {
        this.renderFail(sessionKey)
      }
    },
    renderFail(sessionKey) {
      let me = this
      let msgList = me.data.chatMsg
      console.log(msgList)
      msgList.map((item) => {
        if (item.mid.substring(item.mid.length - 10) == curMsgMid.substring(curMsgMid.length - 10)) {
          item.msg.data[0].isFail = true
          item.isFail = true

          me.setData({
            chatMsg: msgList
          })
        }
      })
      if (me.curChatMsg[0].mid == curMsgMid) {
        me.curChatMsg[0].msg.data[0].isShow = false;
        me.curChatMsg[0].isShow = false
      }
      wx.setStorageSync("rendered_" + sessionKey, msgList);
      isFail = false
    }
  },

  // lifetimes
  created() {},
  attached() {
    this.__visibility__ = true;
    page = 0;
    Index = 0;
  },
  moved() {},
  detached() {
    this.__visibility__ = false;
  },
  ready(event) {
    let me = this;
    app.util.request({
      'url': 'entry/wxapp/Hzbingli.url',
      success: function(res) {
        console.log(res)
        me.setData({
          url: res.data,
        })
      }
    })
    if (getApp().globalData.isIPX) {
      this.setData({
        isIPX: true
      })
    }
    let username = this.data.username;
    let myUsername = wx.getStorageSync("myUsername");
    var z_thumbs = wx.getStorageSync('z_thumbs')
    var user_thumbs = wx.getStorage({ //获取本地缓存
      key: "u_thumb",
      success: function(res) {
        console.log(res)
        me.setData({
          user_thumbs: res.data
        });
      },
    })
    var sate = wx.getStorageSync('sate')
    let sessionKey = username.groupId ?
      username.groupId + myUsername :
      username.your + myUsername;
    this.setData({
      z_thumbs: z_thumbs,
      sate: sate
    })
    let chatMsg = wx.getStorageSync(sessionKey) || [];

    this.renderMsg(null, null, chatMsg, sessionKey);
    wx.setStorageSync(sessionKey, null);
    // disp.on("em.chat.sendSuccess", function(mid){
    // 	curMsgMid = mid
    // 	console.log('发送过去了', mid)
    // 	let msgList = me.data.chatMsg
    // 	msgList.map((item) =>{
    // 		if (item.mid.substring(item.mid.length - 10) == mid.substring(mid.length - 10)) {

    // 			console.log(111111, item)

    // 			item.msg.data[0].isSuc = true
    // 			item.isSuc = true

    // 			me.setData({
    // 				chatMsg: msgList
    // 			})
    // 		}
    // 	})
    // 	if (me.curChatMsg[0].mid == curMsgMid) {
    // 		me.curChatMsg[0].msg.data[0].isShow = true
    // 		me.curChatMsg[0].isShow = true
    // 	}
    // 	wx.setStorageSync("rendered_" + sessionKey, msgList);
    // 	console.log('msgList', msgList)

    // })

    disp.on('em.xmpp.error.sendMsgErr', function(err) {
      curMsgMid = err.data.mid
      isFail = true
      return
      console.log('发送失败了')
      let msgList = me.data.chatMsg
      msgList.map((item) => {
        if (item.mid.substring(item.mid.length - 10) == curMsgMid.substring(curMsgMid.length - 10)) {
          item.msg.data[0].isFail = true
          item.isFail = true

          me.setData({
            chatMsg: msgList
          })
        }
      })
      if (me.curChatMsg[0].mid == curMsgMid) {
        me.curChatMsg[0].msg.data[0].isShow = false;
        me.curChatMsg[0].isShow = false
      }
      wx.setStorageSync("rendered_" + sessionKey, msgList);
    });

    msgStorage.on("newChatMsg", function(renderableMsg, type, curChatMsg, sesskey) {
      me.curChatMsg = curChatMsg;
      console.log(curChatMsg)
      if (!me.__visibility__) return;
      // 判断是否属于当前会话
      if (username.groupId) {
        // 群消息的 to 是 id，from 是 name
        if (renderableMsg.info.from == username.groupId || renderableMsg.info.to == username.groupId) {
          if (sesskey == sessionKey) {
            me.renderMsg(renderableMsg, type, curChatMsg, sessionKey, 'newMsg');
          }

        }
      } else if (renderableMsg.info.from == username.your || renderableMsg.info.to == username.your) {
        if (sesskey == sessionKey) {
          me.renderMsg(renderableMsg, type, curChatMsg, sessionKey, 'newMsg');
        }
      }

    });


  },

});